//
//  MyOrderViewController.m
//  JiFengDaRen
//
//  Created by guest on 16/1/31.
//  Copyright © 2016年 SH_iOS. All rights reserved.
//
#import "CSPayCenterViewController.h"
#import "MyOrderViewController.h"
#import "FinishOrderViewController.h"
#import "NoFinishOrderViewController.h"
@interface MyOrderViewController ()<UIPageViewControllerDataSource,UIPageViewControllerDelegate,UIScrollViewDelegate>
{
    UIView                     *_topView;
    UIView                     *_indicatorView;
    NSMutableArray             *_vcArray;
    UIPageViewController       *_pageVC;
    UIScrollView               *_titleScrollView; //指示当前页
    NSInteger                  _curPage;//指示当前页码
    NSMutableArray             *_storeDatalist;//存放商家信息
   

}
@end

@implementation MyOrderViewController
-(void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createTitleScroll];
    [self createSubVC];
    [self createPageVC];
}
#pragma mark --------实现连动
static CGFloat W;
//创建标题栏
- (void)createTitleScroll
{   self.title = @"订单中心";
    self.view.backgroundColor = [UIColor whiteColor];
    _topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 44)];
    [self.view addSubview:_topView];
    W = KScreenWidth / 2;
    NSArray *titltArr = @[@"未完成",@"已完成"];
    //创建按钮
    for (int i = 0; i < titltArr.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake( i * W,0, W, 44);
        [btn setTitle:titltArr[i]  forState:UIControlStateNormal];
        btn.titleLabel.font = KBoldFont(17.0f);
        btn.backgroundColor = [UIColor whiteColor];
        if (i == 0) {
          [btn setTitleColor:KBaseColor forState:UIControlStateNormal];
        }else{
         [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        }
        
        
        //添加点击事件
        [btn addTarget:self action:@selector(jumpToVC:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = 100+i;
        
        [_topView addSubview:btn];
    }
    
    //navigationbar高度44

    _indicatorView = [[UIView alloc]initWithFrame:CGRectMake(0,42,W, 2)];
    _indicatorView.backgroundColor = KBaseColor;
    [_topView addSubview:_indicatorView];
    
    
}

//构建数据源
- (void)createSubVC
{
    _vcArray = [[NSMutableArray alloc]init];
    NoFinishOrderViewController *noFinishOrder = [[NoFinishOrderViewController alloc]init];
    noFinishOrder.index = 0;
    noFinishOrder.jumpTopPayCente = ^(NSString *state ,NSString *orderId,NSString * money){
        if ([state isEqualToString:@"立即付款"]) {
//            ScanResultViewController *pay =  [[ScanResultViewController alloc]init];
//            pay.order_id = orderId;
//            pay.using_type = 5;
//            pay.money = money;
//            pay.title = @"向商家付款";
//            [self.navigationController pushViewController:pay   animated:YES];
            CSPayCenterViewController  *pay = [[CSPayCenterViewController  alloc]init];
            pay.order_id = orderId;
            pay.orderPayId = @([orderId longLongValue]);
            pay.using_type = @(5);
            pay.total_money = money;
            [self.navigationController pushViewController:pay animated:YES];

        }else if([state isEqualToString:@"确认收货"]){
           [Tool alertWithMessage:@"确认收货之后,货款将会打给店家,是否确认收货。" who:self goin:^{
               
               [MyDataService requestAFURL:[NSString stringWithFormat:KUpdateStoreOrder,[orderId intValue]] httpMethod:@"PUT" params:@{@"status":@(199)} data:nil complection:^(id result) {
                   
                       if ([result[@"success"] isEqualToNumber:@(1)]) {
//                           JudgeViewController *judgeVc = [[JudgeViewController alloc]init];
//                           judgeVc.orderId = orderId;
//                           [self.navigationController pushViewController:judgeVc animated:YES];
                       }
                   } failure:^(id erro) {
                       
                   }];
               
        
           } goout:^{
               
           }];
        }else if([state isEqualToString:@"立即评价"]){
//            JudgeViewController *judgeVc = [[JudgeViewController alloc]init];
//            judgeVc.orderId = orderId;
//
//            [self.navigationController pushViewController:judgeVc animated:YES];
        }
    };

    FinishOrderViewController *finishOrder = [[FinishOrderViewController  alloc]init];
    finishOrder.index = 1;
    finishOrder.jumpTopPayCente = ^(NSString *state,NSString *orderId,NSString *money){
      

        if ([state isEqualToString:@"立即评价"]) {
            [MyDataService requestAFURL:[NSString stringWithFormat:KUpdateStoreOrder,[orderId intValue]] httpMethod:@"PUT" params:@{@"status":@(199)}data:nil complection:^(id result) {
            
//                if ([result[@"success"] isEqualToNumber:@(1)]) {
//                    JudgeViewController *judgeVc = [[JudgeViewController alloc]init];
//                    judgeVc.orderId = orderId;
//                    [self.navigationController pushViewController:judgeVc animated:YES];
//                }
            } failure:^(id erro) {
                
            }];
           
        }
    };
    [_vcArray addObject:noFinishOrder];
    [_vcArray addObject:finishOrder];
    
}

- (void)push:(UIViewController *)vc
{
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)createPageVC
{
    _pageVC = [[UIPageViewController alloc]initWithTransitionStyle:1 navigationOrientation:0 options:nil];
    _pageVC.delegate = self;
    _pageVC.dataSource = self;
    [_pageVC setViewControllers:@[_vcArray[0]] direction:1 animated:NO completion:nil];
    
    _pageVC.view.frame = CGRectMake(0,44, self.view.frame.size.width, KScreenHeight - 44);
    [self.view addSubview:_pageVC.view];
    
    //遍历pageVC.view的子视图，找到scrollview
    for (UIView *view in _pageVC.view.subviews) {
        if ([view isKindOfClass:[UIScrollView class]]) {
            //使用kvc赋值
            [view setValue:self forKeyPath:@"delegate"];
            //            ((UIScrollView *)view).delegate =self;
        }
    }
}

//跳转到对应的界面
- (void)jumpToVC:(UIButton *)btn
{
    //当前界面索引
    //    NSInteger curPage = [_vcArray indexOfObject:_pageVC.viewControllers[0]];
    //要跳转到的vc索引
    //direction：0代表前进，1代表后退
    NSInteger toPage = btn.tag - 100;
    [_pageVC setViewControllers:@[_vcArray[toPage]] direction:_curPage>toPage animated:YES completion:^(BOOL finished) {
        _curPage = toPage;
    }];
}

#pragma mark - PageVCDelegate
//返回下一页VC
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
    //拿到当前显示的vc对应在数组中的索引
    NSInteger index = [_vcArray indexOfObject:viewController];
    //如果当前显示的已经是最后一页
    if (index == _vcArray.count -1) {
        return nil;
    }
    return _vcArray[index+1];
}
//返回上一页
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
    NSInteger index = [_vcArray indexOfObject:viewController];
    if (index == 0) {
        return nil;
    }
    return _vcArray[index-1];
}

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed
{
    // NSLog(@"completed!");
    _curPage = [_vcArray indexOfObject:_pageVC.viewControllers[0]];
    //NSLog(@"%ld",_curPage);
}

#pragma mark - ScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //NSLog(@"%f",scrollView.contentOffset.x);
    //初值为375，结束值仍然为375
    CGFloat width = self.view.frame.size.width;
    CGFloat offsetX = scrollView.contentOffset.x;
    
    //计算indicatorView实际偏移量
    CGFloat offSetXInd = (offsetX - width) * (W/self.view.frame.size.width)+ _curPage*W;
    for (UIView *view in _topView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            
            UIButton *btn = (UIButton *)view;
            if (btn.tag == 100 + _curPage) {
              [btn setTitleColor:KBaseColor forState:UIControlStateNormal];
                
            }else{
                
               [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                
            }
        }
    }
    _indicatorView.frame = CGRectMake( offSetXInd  ,42, W, 2);
   // CGFloat maxX = CGRectGetMaxX(_indicatorView.frame);
//    CGFloat titleWidth = _titleScrollView.frame.size.width;
//    if ( maxX >= titleWidth ) {
//        _titleScrollView.contentOffset = CGPointMake(maxX - titleWidth, 0);
//    }
    
}

-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{    CGFloat offsetY  =  scrollView.contentOffset.y;
    offsetY = 0;
    
    

    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
